<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: jinzhao
 * Date: 16-8-10
 * Time: 下午5:39
 */
class Account extends CI_Controller{
    public function index()
    {
        $this->register();
    }
    
    public function register()
    {
        $this->load->helper('form');

        $data = array(
            'errmsg' => ''
        );
        $this->load->view('register.html', $data); 
    }
    
    public function register_result()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');
        
        $ret = $this->form_validation->run('userinfo');
        if (!$ret){
            $this->index();
            return;
        }
        
        $email = $this->input->post('email');
        $password = $this->input->post('password');
        $rand_login = $this->make_rand();
        $rand_register = $this->make_rand();
        $userinfo = array(
            'email' => $email,
            'password' => $password,
            'rand_register' => $rand_register
        );
        
        $this->load->model('user_model');
        $result = $this->user_model->insert($userinfo);
        if (!$result) {
            $data = array(
                'errmsg' => '用户名已存在'
            );
            $this->load->view('register.html', $data);
            return;
        }
        $this->email_validation($email, $rand_register);
        $data = array(
            'code' => '0',
            'msg' => '恭喜，注册成功，请登录邮箱进行账号认证'
        );
        $this->load->view('account.html', $data);
    }
    
    public function active()
    {
        $data = array(
            'code' => '-1',
            'msg' => '账户尚未激活，请先激活'
        );
        $this->load->view('account.html', $data);
        return;
        
    }
    
    public function send_verification()
    {
        $email = $this->session->userdata('email'); 
        $rand_register = $this->make_rand();
        
        $this->load->model('user_model');
        $this->user_model->update(array('email' => $email) ,array('rand_register' => $rand_register));
        $this->email_validation($email, $rand_register);
        $data = array(
            'code' => '0',
            'msg' => '激活信息已发送至您的邮箱，请登录邮箱进行认证'
        );
        $this->load->view('account.html', $data);
    }

    //账户验证
    public function verification()
    {
        
        $param = $this->input->get('param');
        $query = base64_decode($param, true);
        $params = explode('&', $query);

        foreach ($params as $arg){
            $key_val = explode('=', $arg);
            ${$key_val[0]} = $key_val[1];
        }
        $this->load->model('user_model');
        $result = $this->user_model->get_by_email($email);
        if ($result === false){
            $data = array(
                'msg' => '认证失败，此用户不存在'
            );
            $this->load->view('account.html', $data); 
            return;
        }

        $this->session->set_userdata('email', $email);
        $this->session->set_userdata('uid', $result['id']);
        
        $exp = 60 * 60 * 4; //4小时有效期
        if (time() - $timestamp > $exp){
            $data = array(
                'code' => '-1',
                'msg' => '认证已过期，请重新获取认证信息'
            );
            $this->load->view('account.html', $data);
            return;
        }
        if ($sign != $result['rand_register']){
            $data = array(
                'code' => '-1',
                'msg' => '激活失败'
            );
            $this->load->view('account.html', $data);
            return;
        }

        $data = array(
            'code' => '0',
            'msg' => '激活成功'
        );
        
        $this->load->model('user_model');
        $where = array(
            'email' => $email  
        );
        $set = array(
            'rand' => $this->make_rand(),
            'active' => 1
        );
        $this->user_model->update($where, $set);
        
        $this->session->set_userdata('rand', $set['rand']);
        
        $this->load->view('account.html', $data);
    }
    

    
    private function email_validation($email = '', $rand='')
    {
        $query = array(
            'user' => $email,
            'timestamp' => time(),
            'sign' => $rand
        );

        $link = $this->create_link($query);
        
        $this->load->library('email');
        $this->email->from('isee8583@163.com', 'isee8583');
        $this->email->to($email);
        $this->email->subject('isee8583账号激活');
        $this->email->message($link);
        $this->email->send();
    }
    
    private function make_rand($length = 32)
    {
        $chars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $number = '';
        for($i = 0; $i < 32; $i++){
           $number .= $chars[mt_rand(0, 61)]; 
        }
        return $number; 
    }
    
    private function create_link($query = '')
    {
        $base64_query = sprintf('email=%s&timestamp=%s&sign=%s', $query['user'], $query['timestamp'], $query['sign']);
        $base64_query = base64_encode($base64_query);

        $this->load->helper('url');
        $link = sprintf('%saccount/verification?param=%s', base_url(), $base64_query);
        return $link;
    }
    
    public function password()
    {
        $this->load->helper('form');
        $data['email'] = $this->session->userdata('email');
        $this->load->view('password.html', $data);
    }
    
    public function change_password()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->model('user_model');
        $result = $this->form_validation->run('change_password');
        if (!$result){
            $data['email'] = $this->session->userdata('email');
            $this->load->view('password.html', $data);
            return;
        }
        $old = $this->input->post('old_password');
        $new = $this->input->post('new_password');
        $new2 = $this->input->post('new_password2');
        
        $old = md5($old);
        $new = md5($new);
        $new2 = md5($new2);
        
        
        $result = $this->user_model->get_by_email($this->session->userdata('email'));
        if (!$result){
            $data['display_error'] = '用户名不存在';
            $data['email'] = $this->session->userdata('email');
            $this->load->view('password.html', $data);
            return;
        }
        if ($old !== $result['password']){
            $data['display_error'] = '密码错';
            $data['email'] = $this->session->userdata('email');
            $this->load->view('password.html', $data);
            return;
        }
        if ($new !== $new2){
            $data['display_error'] = '两次输入密码不匹配';
            $data['email'] = $this->session->userdata('email');
            $this->load->view('password.html', $data);
            return;
        }
        $result = $this->user_model->update(array('email' => $this->session->userdata('email')), array('password' => $new));
        if (!$result){
            $data['display_error'] = '密码修改失败';
            $data['email'] = $this->session->userdata('email');
            $this->load->view('password.html', $data);
            return;
        }
        $data['code'] = '0';
        $data['msg'] = '密码修改成功';
        $this->load->view('account.html', $data);
    }
    
    
}